<template>
    <div class="box">
        <div class="clearfix" v-show="showHide4">
            <el-container>
                <div class="mostTop"></div>
                <el-header class="clearfix">
                    <p class="allCourseTitle">所有课程</p>

                    <p class="allCourseRoute return" @click="backed">首页 > 所有课程</p>

                    <!-- <p class="allCourseRoute"><span @click="goHome()">首页</span> > 所有课程</p> -->

                </el-header>
                <div class="listModel" v-show="showHide1">
                    <div class="btnPart clearfix">
                        <el-button type="primary" @click="delList()">删除选择</el-button>
                        <el-button type="primary" plain @click="goImg()">大图模式</el-button>
                        <el-button type="success" class="btnRight" @click="goAdd()">新增课程</el-button>
                    </div>
                    <el-main>
                        <div>
                            <el-table
                                    ref="multipleTable"
                                    :data="tableData"
                                    tooltip-effect="dark"
                                    style="width: 100%"
                                    @selection-change="handleSelectionChange">
                                <el-table-column
                                        type="selection"
                                        style="width: 10%">
                                </el-table-column>
                                <el-table-column
                                        prop="courseName"
                                        label="课程名称"
                                        style="width: 20%">
                                </el-table-column>
                                <el-table-column
                                        prop="teacherName"
                                        label="课程老师"
                                        style="width: 14%">
                                </el-table-column>
                                <el-table-column
                                        prop="courseDuration"
                                        label="课程时长(周)"
                                        style="width: 14%"
                                >
                                </el-table-column>
                                <el-table-column
                                        prop="courseStartTime"
                                        label="开课时间"
                                        style="width: 14%"
                                        show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                        prop="managerName"
                                        label="发布人员"
                                        style="width: 14%"
                                        show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                        prop="option"
                                        label="操作"
                                        style="width: 14%"
                                        show-overflow-tooltip>
                                    <template slot-scope="scope">
                                        <el-button
                                                size="mini"
                                                @click="goCourseDescList(scope.$index, scope.row)">
                                            查看
                                        </el-button>
                                        <el-button
                                                size="mini"
                                                @click="edit(scope.$index, scope.row)">
                                            编辑
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-main>
                </div>
                <div class="imgModel" v-show="showHide2">
                    <div class="btnPart clearfix">
                        <el-button type="primary" plain @click="goList()">列表模式</el-button>
                        <el-button type="success" class="btnRight" @click="goAdd()">新增课程</el-button>
                    </div>
                    <div class="content">
                        <ul class="clearfix">
                            <li v-for="v in tableData">
                                <img :src="v.courseImage" alt="">
                                <p class="courseName">{{v.courseName}}</p>
                                <div class="listTit clearfix">
                                    <p class="title">开课时间</p>
                                    <p class="con">{{v.courseStartTime}}</p>
                                </div>
                                <div class="listTit clearfix">
                                    <p class="title">课程时长</p>
                                    <p class="con">{{v.courseDuration}}周</p>
                                </div>
                                <div class="listTit clearfix">
                                    <p class="title">课程老师</p>
                                    <p class="con">{{v.teacherName}}</p>
                                </div>
                                <div class="btnImg">
                                    <el-button type="success" @click="goCourseDescImg($event)" :id="v.id">查看详情
                                    </el-button>

                                    <el-button type="info" @click="delImg($event)" :id="v.id">删除</el-button>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
            </el-container>
            <el-pagination
                    :page-size="10"
                    @current-change="handleCurrentChange"
                    layout="prev, pager, next"
                    :total="total"
                    :current-page.sync="currentPage">
            </el-pagination>
        </div>
        <div class="edit" v-show="showHide3">
            <!--<div class="edit" v-show="true">-->
            <el-container>
                <div class="mostTop"></div>
                <el-header class="clearfix">
                    <p class="addCourseTitle">编辑课程</p>
                    <p class="return" @click="cancel()">< 返回</p>
                </el-header>
                <el-main>
                    <p class="courseDetails">基本信息</p>
                    <div class="inputTitle clearfix">
                        <div class="left">
                            <p>课程名称</p>
                            <el-input v-model="courseName" placeholder="课程名称"></el-input>
                            <p>课程介绍</p>
                            <el-input
                                    type="textarea"
                                    :rows="4"
                                    placeholder="课程介绍"
                                    v-model="courseDesc">
                            </el-input>
                            <p>授课教师</p>
                            <div class="select">
                                <el-select v-model="departmentName" placeholder="选择部门" class="selectChildren"
                                           @change="departmentChoose()">
                                    <el-option
                                            v-for="(item) in options1"
                                            :key="item.id"
                                            :label="item.departmentName"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                                <el-select v-model="teacherName" placeholder="选择老师" class="selectChildren"
                                           @change="teacherChoose()">
                                    <el-option
                                            v-for="item in options2"
                                            :key="item.id "
                                            :label="item.name"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                            </div>
                            <p>课程图片</p>
                            <!-- <div class="img">
                                <img src="../assets/test.jpg" alt="">
                            </div>
                            <el-upload
                                    :on-preview="handlePreview"
                                    action="https://jsonplaceholder.typicode.com/posts/"
                            >
                                <el-button size="small" type="primary" class="imgUpBtn">点击上传</el-button>
                                <div slot="tip" class="el-upload__tip">单文件大小请在1M以内,仅支持JPG、JPEG、PNG格式</div>
                            </el-upload> -->
                            <div slot="tip" class="el-upload__tip">
                                单上传头像图片大小不能超过 2MB!,仅支持JPG、JPEG、PNG格式
                            </div>
                            <!-- </el-upload> -->
                            <div id="upload">
                                <el-upload
                                        class="avatar-uploader"
                                        action="/image"
                                        :show-file-list="false"
                                        :on-success="handleAvatarSuccess"
                                        :before-upload="beforeAvatarUpload"
                                        name="uploadFile"
                                >
                                    <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                            </div>
                        </div>
                        <div class="right">
                            <p>开课时间</p>
                            <div class="block">
                                <el-date-picker
                                        v-model="courseStartTime"
                                        type="date"
                                        placeholder="选择日期"
                                        format="yyyy-MM-dd"
                                        class="date"
                                        :picker-options="timeLimit">
                                </el-date-picker>
                            </div>
                            <p>持续时间</p>
                            <el-input v-model="courseDuration" placeholder="持续时间"></el-input>
                            <p>上课地址</p>
                            <el-input v-model="courseAddress" placeholder="上课地址"></el-input>
                        </div>
                    </div>
                </el-main>
            </el-container>
            <div id="footBox">
                <div id="footer">
                    <el-button type="info" @click="cancel()">取消</el-button>
                    <el-button type="success" @click="ok()">保存</el-button>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
    export default {
        name: "Course",
        data() {
            return {
                timeLimit:{
                    disabledDate(time){
                        return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
                    }
                },
                imageUrl: "",
                localhost: '',
                currentPage: 1,
                total: 0,
                showHide1: true,
                showHide2: false,
                showHide3: false,
                showHide4: true,
                //表格数据
                tableData: [],
                id: '',
                courseName: '',
                courseDesc: '',
                courseStartTime: '',
                courseDuration: '',
                courseAddress: '',
                managerName: '',
                options1: [],
                options2: [],
                departmentName: '',
                departmentId: '',
                teacherName: '',
                teacherId: '',
                multipleSelection: '',
                delImgId: '',
            }
        },
        methods: {
            //分页
            handleCurrentChange: function (currentPage) {
                this.currentPage = currentPage;
                this.Rendering()
            },
            //列表模式多选删除id获取
            handleSelectionChange(val) {
                var selected = [];
                for (var i = 0; i < val.length; i++) {
                    selected.push(val[i].id)
                }
                this.multipleSelection = selected;
                //console.log(this.multipleSelection);
            },
            //去首页
            goHome() {
                this.$router.push({path: '/index'})
            },
            //列表模式删除
            delList() {
                if (this.multipleSelection==''){
                    this.$message({
                        type: 'warning',
                        message: '请选择需删除课程'
                    });
                }else{
                    this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.$axios({
                            method: 'post',
                            url: '/course/delete',
                            data: {
                                ids: this.multipleSelection
                            },
                        }).then((res) => {
                            if (res.data.msg=='操作成功'){
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                });
                                this.Rendering();
                            }else {
                                this.$message({
                                    type: 'info',
                                    message: '删除失败'
                                });
                            }
                            //console.log(res)
                        });

                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                }
            },
            //大图模式删除
            delImg(a) {
                //console.log(a.currentTarget.id);
                var id = a.currentTarget.id;
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios({
                        method: 'post',
                        url: '/course/delete',
                        data: {
                            ids: [id]
                        },
                    }).then((res) => {
                        if (res.data.msg=='操作成功'){
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.Rendering()
                        }else {
                            this.$message({
                                type: 'info',
                                message: '删除失败'
                            });
                        }
                        //console.log(res)
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            goAdd() {
                this.$router.push({path: '/addCourse'})
            },
            //返回首页
            backed() {
                this.$router.push({path: '/index'})
            },
            //补零规则
            add0(m) {
                return m < 10 ? '0' + m : m
            },
            //将时间戳转换为日期格式
            format(shijianchuo) {
                //时间戳是整数，否则要parseInt转换
                var time = new Date(shijianchuo);
                var y = time.getFullYear();
                var m = time.getMonth() + 1;
                var d = time.getDate();
                return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ';
            },
            //部门选择改变事件
            departmentChoose() {
                this.options2 = [];
                this.teacherName = '';
                for (var i = 0; i < this.options1.length; i++) {
                    if (this.options1[i].departmentName == this.departmentName) {
                        this.departmentName = this.options1[i].id
                    }
                }
                this.$axios({
                    method: 'get',
                    url: '/teacher/findTeacherByWhere',
                    params: {
                        limit: 20000,
                        departmentId: this.departmentName
                    }
                }).then((res) => {
                    //console.log(res.data.data.list);
                    this.options2 = res.data.data.list
                }).catch((err) => {
                });
                // console.log(this.options1);
                // console.log(this.departmentName);
            },
            //教师选择改变事件
            teacherChoose() {
                for (var i = 0; i < this.options2.length; i++) {
                    if (this.options2[i].teacherName == this.teacherName) {
                        this.teacherName = this.options2[i].id
                    }
                }
                //console.log(this.options2);
                //console.log(this.teacherName);
            },
            //编辑方法回显
            edit(index, row) {
                //console.log(row)
                this.showHide3 = !this.showHide3;
                this.showHide4 = !this.showHide4;
                //请求部门接口
                this.$axios({
                    method: 'post',
                    url: '/teacher/findAllDepartment',
                }).then((res) => {
                    //console.log(res.data.data);
                    this.options1 = res.data.data;
                }).catch((err) => {

                });
                //数据回显 请求的课程描述接口
                this.$axios({
                    url: `/course/desc/${row.id}`,
                    params: row.id,
                }).then((res) => {
                    this.id = res.data.data.id;
                    this.courseName = res.data.data.courseName;
                    this.courseDesc = res.data.data.courseDesc;
                    this.departmentName = res.data.data.departmentName;
                    this.teacherName = res.data.data.teacherName;
                    this.teacherId = res.data.data.teacherId;
                    this.departmentId = res.data.data.departmentId;
                    this.managerName = res.data.data.managerName;
                    this.imageUrl = res.data.data.courseImage;
                    this.courseStartTime = res.data.data.courseStartTime;
                    this.courseDuration = res.data.data.courseDuration;
                    this.courseAddress = res.data.data.courseAddress;
                    //console.log(res);
                    this.$axios({
                        method: 'get',
                        url: '/teacher/findTeacherByWhere',
                        params: {
                            limit: 20000,
                            departmentId: this.departmentId
                        }
                    }).then((res) => {
                        this.options2 = res.data.data.list
                    }).catch((err) => {
                    });
                    //console.log(res.data.data);
                }).catch((err) => {
                    //console.log(err)
                });

            },
            //编辑图片上传返回地址
            handleAvatarSuccess(res, file) {
                //this.localhost = URL.createObjectURL(file.raw);
                this.imageUrl = res.data;
                // console.log(res.data)
                // console.log(file)
                // console.log(this.imageUrl)
            },
            //编辑里的保存按钮
            ok() {
                var reg=/^[0-9]*$/;
                if (this.courseDesc==''){
                    this.$message({
                        type: 'error',
                        message:'课程描述不能为空'
                    });
                }else if (this.courseDuration==''){
                    this.$message({
                        type: 'error',
                        message:'课程持续时间不能为空'
                    });
                }else if (this.imageUrl==''){
                    this.$message({
                        type: 'error',
                        message:'没有上传课程图片'
                    });
                }else if (this.courseAddress==''){
                    this.$message({
                        type: 'error',
                        message:'上课地址不能为空'
                    });
                }else if (!reg.test(this.courseDuration)){
                    this.$message({
                        type: 'error',
                        message:'课程持续时间请输入数字'
                    });
                } else {
                    //this.teacherName = this.teacherId;
                    this.$axios({
                        method: 'post',
                        url: '/course/update',
                        data: {
                            courseAddress: this.courseAddress,
                            courseDesc: this.courseDesc,
                            courseDuration: this.courseDuration,
                            courseImage: this.imageUrl,
                            courseName: this.courseName,
                            courseStartTime: this.courseStartTime,
                            id: this.id,
                            managerName: this.managerName,
                            teacherId: this.teacherName,
                        }
                    }).then((res) => {
                        console.log(this.teacherId);
                        if (res.data.code==50010){
                            this.$message({
                                type: 'error',
                                message:'课程名称重复'
                            });
                        }else if (res.data.msg=='课程持续时间在1~48周'){
                            this.$message({
                                type: 'error',
                                message:'课程持续时间在1~48周'
                            });
                        }else if (res.data.msg=='课程名不能为空'){
                            this.$message({
                                type: 'error',
                                message:res.data.msg
                            });
                        }else if (res.data.msg=='success'){
                            this.$message({
                                type: 'success',
                                message:'修改成功'
                            });
                            this.leave();
                            location.reload();
                        }

                    }).catch((err) => {

                    });
                }

                //console.log(this.imageUrl);
            },
            //编辑里面的取消按钮
            cancel() {
                this.$confirm('此操作将离开本页面，修改内容未保存, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$message({
                        type: 'success',
                        message: '取消成功!'
                    });
                    this.showHide4 = !this.showHide4;
                    this.showHide3 = !this.showHide3
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消离开!'
                    });
                });
            },
            //离开编辑页到课程列表
            leave(){
                this.showHide4 = !this.showHide4;
                this.showHide3 = !this.showHide3
            },
            //列表模式查看（去课程详情页面）
            goCourseDescList(index, row) {
                //console.log(row);
                this.$router.push({path: '/courseDesc', query: {id: row.id}})
            },
            //大图模式查看（去课程详情页面）
            goCourseDescImg(a) {
                //console.log(a.currentTarget.id);
                this.$router.push({path: '/courseDesc', query: {id: a.currentTarget.id}})
            },
            //去大图模式
            goImg() {
                this.showHide1 = !this.showHide1;
                this.showHide2 = !this.showHide2
            },
            //去列表模式
            goList() {
                this.showHide2 = !this.showHide2;
                this.showHide1 = !this.showHide1
            },
            //请求课程接口封装渲染页面
            Rendering() {
                this.$axios({
                    url: '/course/list',
                    params: {
                        page: this.currentPage,
                        limit: 10
                    }
                }).then((res) => {
                  if(res.data.code==0){
                       this.total = res.data.data.total;
                    var data = res.data.data.list;
                    //console.log(data)
                    for (var i = 0; i < data.length; i++) {
                        data[i].courseStartTime = this.format(data[i].courseStartTime)
                    }
                    this.tableData = data;
                  }else {
                    this.$router.push("/noResponse");
                    if (res.data.code == 0) {
                        this.$router.push("/administrator");
                    }
                  }  
                }).catch((err) => {
                    //console.log(err)
                })
            },
            //图片本地上传到页面
            beforeAvatarUpload(file) {
                const isJPG = file.type === "image/jpeg";
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error("上传头像图片只能是 JPG 格式!");
                }
                if (!isLt2M) {
                    this.$message.error("上传头像图片大小不能超过 2MB!");
                }
                return isJPG && isLt2M;
            },
        },
        mounted() {
            //调用课程请求接口函数
            this.Rendering();

        }
    }
</script>
<style lang="less" scoped>
    .clearfix:after {
        content: '';
        clear: both;
        display: block;
    }

    li {
        list-style: none;
    }

    .mostTop {
        height: 10px;
        background: #f2f2f6;
    }

    .listModel {
        width: 100%
    }

    .el-header {
        background-color: #fff;
        margin-top: 10px;
        line-height: 30px;

        .allCourseTitle {
            color: #333;
            float: left;
            font-size: 18px;
        }

        .allCourseRoute {
            color: #333;
            float: right;
            font-size: 18px;

            span:hover {
                color: #8cc5ff;
                cursor: pointer;
            }
        }

        .return {
            color: #333;
            float: right;
            font-size: 18px;
            cursor: pointer;
        }

        .return:hover {
            color: #8cc5ff;
        }
    }

    .btnPart {
        padding: 10px;
        background: #f2f2f6;
        margin: 10px
    }

    .btnRight {
        float: right;
    }

    .el-main {
        background-color: #fff;
        color: #333;
    }

    .content {
        margin: 0;
        padding: 0;

        ul {
            margin: 0;
            padding: 0;

        }

        li {
            float: left;
            margin-top: 20px;
            margin-left: 1%;
            margin-right: 1%;
            width: 31%;
            height: 630px;
            background: #f2f2f6;

            img {
                width: 100%;
                height: 350px;
            }

            .courseName {
                margin-left: 15px;
                font-size: 18px;
                color: #666666;
            }

            .listTit {
                border-bottom: 2px solid #fff;

                .title {
                    float: left;
                    margin-left: 15px;
                }

                .con {
                    font-family: '宋体';
                    float: right;
                    margin-right: 15px;
                    color: #666666;
                }
            }

            .btnImg {
                margin-left: 30%;
                margin-top: 5px;
            }
        }
    }

    body > .el-container {
        margin-bottom: 40px;
    }

    .el-pagination {
        float: right;
    }

    .edit {
        .el-header {
            background-color: #fff;
            margin-top: 10px;
            line-height: 30px;

            .addCourseTitle {
                color: #333;
                float: left;
                font-size: 18px;
            }

            .return {
                color: #333;
                float: right;
                font-size: 18px;
                cursor: pointer;
            }

            .return:hover {
                color: #8cc5ff;
            }
        }

        .el-main {
            margin-top: 10px;
            background-color: #fff;
            color: #333;

            .courseDetails {
                font-weight: bold;
            }

            .inputTitle {
                width: 100%;

                .left {
                    float: left;
                    width: 47%;

                    .select {
                        width: 100%;

                        .selectChildren {
                            width: 50%;
                        }
                    }

                    // .img {
                    //     width: 150px;
                    //     height: 150px;
                    //     img {
                    //         width: 100%;
                    //         height: 100%;
                    //     }
                    // }
                    // .imgUpBtn{
                    //     margin-left: 30px;
                    //     margin-top: 10px;
                    // }
                    #upload {
                        width: 178px;
                        height: 178px;
                        border: 1px dashed #6b6767;
                        border-radius: 6px;
                        cursor: pointer;
                        position: relative;
                        overflow: hidden;
                    }

                    .avatar-uploader .el-upload {
                        border: 1px dashed #cfa1a1;
                        border-radius: 6px;
                        cursor: pointer;
                        position: relative;
                        overflow: hidden;
                    }

                    .avatar-uploader .el-upload:hover {
                        border-color: #409eff;
                    }

                    .avatar-uploader-icon {
                        font-size: 28px;
                        color: #587397;
                        width: 178px;
                        height: 178px;
                        line-height: 178px;
                        text-align: center;
                    }

                    .avatar {
                        width: 178px;
                        height: 178px;
                        display: block;
                    }
                }

                .right {
                    margin-left: 6%;
                    float: left;
                    width: 47%;

                    .date {
                        width: 100%;
                    }

                    .selectTeacher {
                        width: 100%;
                    }
                }
            }
        }

        #footBox {
            width: 100%;
            height: 350px;
            background: white;
        }

        #footer {
            margin-left: 43%;
            height: 200px;

            .el-button {
                float: left;
                margin-top: 100px;
            }
        }
    }
</style>